# Api中间件层, 所以关于Api的请求都必须经过此中间件
# 用户权限认证
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.http import HttpResponse
from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict
from BloodSpiderAPI.models import User

# 从请求中获取uid并验证用户是否存在
def get_and_validate_user(request):
    """
    从请求中获取uid并验证用户是否存在
    :param request: Django请求对象
    :return: User对象或None
    """
    try:
        # 根据请求方法获取uid
        if request.method == "GET":
            uid = request.GET.get("uid")
        elif request.method == "POST":
            uid = request.POST.get("uid")
        else:
            return None
            
        # 从数据库中查询用户
        if uid:
            return User.objects.get(uid=uid)
        return None
    except User.DoesNotExist:
        return None

def is_route_in_list(request):
    """
    判断当前请求的路由是否在指定的路由列表中
    :param request: Django请求对象
    :return: 如果路由在列表中返回True，否则返回False
    """
    # 需要匹配的路由列表
    target_routes = [
        "/api/user/query_user_info/",
    ]
    # 检查当前请求的路径是否在目标列表中
    return request.path in target_routes

class UserPermissionAuthentication(MiddlewareMixin):
    def process_request(self, request):
        request.system_dict = settings.SYSTEM_DICT
        # 获取当前协议头 + 域名
        request.current_host = request.scheme + "://" + request.get_host()
        
        if request.path.startswith("/api/"):
            # 判断当前路由是否需要用户认证
            if is_route_in_list(request) is False:
                # 调用获取和验证用户的函数
                user = get_and_validate_user(request)
                if user:
                    request.user = user
                    return None
                else:
                    return response_dict(code=1, message="非法请求")
        return None
        
  
        
    def process_response(self, request, response):
        return response



